#!/usr/bin/python3
"""
Change DNF Automatic configuration.

The stage changes persistent DNF Automatic configuration. Currently, only
a subset of options can be set:
  - 'commands' section
    - apply_updates
    - upgrade_type
"""


import sys
import iniparse

import osbuild.api


SCHEMA = r"""
"definitions": {
  "commands": {
    "type": "object",
    "additionalProperties": false,
    "description": "'commands' configuration section.",
    "properties": {
      "apply_updates": {
        "type": "boolean",
        "description": "Whether packages comprising the available updates should be installed."
      },
      "upgrade_type": {
        "type": "string",
        "description": "What kind of upgrades to look at.",
        "enum": ["default", "security"]
      }
    }
  }
},
"additionalProperties": false,
"description": "DNF Automatic configuration.",
"properties": {
  "config": {
    "type": "object",
    "additionalProperties": false,
    "description": "configuration definition.",
    "properties": {
      "commands": {
        "$ref": "#/definitions/commands"
      }
    }
  }
}
"""


def bool_to_yes_no(b):
    if b:
        return "yes"
    return "no"


def main(tree, options):
    config = options.get("config")
    dnf_automatic_config_path = f"{tree}/etc/dnf/automatic.conf"
    dnf_automatic_conf = iniparse.SafeConfigParser()

    # do not touch the config file if not needed
    if config is None:
        return 0

    try:
        with open(dnf_automatic_config_path, "r") as f:
            dnf_automatic_conf.readfp(f)
    except FileNotFoundError:
        print(f"Error: DNF automatic configuration file '{dnf_automatic_config_path}' does not exist.")
        return 1

    for config_section, config_options in config.items():
        for option, value in config_options.items():
            if isinstance(value, bool):
                value = bool_to_yes_no(value)
            dnf_automatic_conf.set(config_section, option, value)

    with open(dnf_automatic_config_path, "w") as f:
        dnf_automatic_conf.write(f)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
